package tt.dz.order.log;

import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import tt.dz.order.annotation.OrderLogAnnotation;
import tt.dz.order.dao.BaseDAOUtil;
import tt.dz.order.util.OrderConstant.BizType;
import tt.dz.order.util.UUIDUtil;
import tt.dz.order.vo.LogVO;

@Aspect
@Component
public class LogService implements Ordered {
	private static Logger log = LoggerFactory.getLogger(LogService.class);
	
	private static final String INSERT_LOG = "insert into order_log(log_id,biz_type,biz_code,biz_name,start_time,end_time,param_in,param_out,biz_desc) "
			+ " values(:logId,:bizType,:bizCode,:bizName,:startTime,:endTime,:paramIn,:paramOut,:bizDesc )";
	
	/**
	 * 记录数据库级别日志
	 * @param logVo
	 * @throws Exception
	 */
	public void log(LogVO logVo) throws Exception {
		logVo.setLogId(String.valueOf(UUIDUtil.longUUID()));
		BaseDAOUtil.updateObject(INSERT_LOG, logVo);
	}

	@Around(value = "execution(* tt.dz.order.service..*(..)) && @annotation(tt.dz.order.annotation.OrderLogAnnotation)&& @annotation(orderLogAnnotation)", argNames = "orderLogAnnotation")
	public Object around(ProceedingJoinPoint point, OrderLogAnnotation orderLogAnnotation) throws Throwable {
		Object result = null;
		Object args = point.getArgs();
		Object target = point.getTarget();
		Signature signature = point.getSignature();
		StringBuilder bizDescSB = new StringBuilder();
		LogVO logVo = new LogVO();
		Date startTime = new Date();
		BizType bizType = orderLogAnnotation.bizType();// 业务类型
		String bizCode = orderLogAnnotation.bizCode();// 业务编号
		String bizName = orderLogAnnotation.bizName();// 业务名称
		String bizDesc = orderLogAnnotation.bizDesc();// 描述
		Throwable bizException = null;
		try {
			result = point.proceed();
		} catch (Exception e) {
			bizDescSB.append(e.getMessage());
			bizException = e;
		}
		try {
			bizDescSB.append(bizDesc + ";");
			logVo.setStartTime(startTime);
			logVo.setBizCode(bizCode);
			logVo.setBizName(bizName);
			logVo.setBizType(Integer.valueOf(bizType.toString()));
			logVo.setParamIn(JSON.toJSONString(args));
			Date endTime = new Date();
			bizDescSB.append("执行类：" + target.getClass().getName() + ",方法：" + signature.getName());
			bizDescSB.append(" 耗时" + (endTime.getTime() - startTime.getTime()) + "毫秒。");
			logVo.setParamOut(result != null ? JSON.toJSONString(result) : "");
			logVo.setBizDesc(bizDescSB.toString());
			logVo.setEndTime(endTime);
			log(logVo);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		if(bizException!=null)
			throw bizException;
		
		return result;
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
